package com.service.impl;

import com.service.EsInitService;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import static core.Constants.Es.INDEX_NAME;

@Service
public class EsInitServiceImpl implements EsInitService {
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public EsInitServiceImpl(ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

    @Override
    public void init(String indexName) {
        String mappingJson = "{\n" +
                "  \"properties\": {\n" +
                "    \"id\": {\n" +
                "      \"type\": \"keyword\"\n" +
                "    },\n" +
                "    \"name\": {\n" +
                "      \"type\": \"keyword\"\n" +
                "    },\n" +
                "    \"price\": {\n" +
                "      \"type\": \"double\"\n" +
                "    },\n" +
                "    \"productDesc\": {\n" +
                "      \"type\": \"text\",\n" +
                "      \"analyzer\": \"ik_max_word\"\n" +
                "    }\n" +
                "  }\n" +
                "}";
        elasticsearchRestTemplate.indexOps(IndexCoordinates.of(INDEX_NAME))
                .create(new HashMap<>(), Document.parse(mappingJson));
    }
}
